package com.example.security.filter;

import com.example.security.config.SsoProperties;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.Base64;

@Component
@RequiredArgsConstructor
public class OAuth2ClientAuthenticationFilter extends OncePerRequestFilter {

    private final SsoProperties ssoProperties;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        
        if (request.getRequestURI().equals("/api/oauth/token")) {
            String authorization = request.getHeader("Authorization");
            if (authorization == null || !authorization.startsWith("Basic ")) {
                response.sendError(401, "Unauthorized client");
                return;
            }

            // 解码Basic认证信息
            String credentials = new String(Base64.getDecoder().decode(
                authorization.substring("Basic ".length())));
            String[] values = credentials.split(":", 2);
            
            // 验证客户端凭证
            if (!ssoProperties.getClientId().equals(values[0]) || 
                !ssoProperties.getClientSecret().equals(values[1])) {
                response.sendError(401, "Invalid client credentials");
                return;
            }
        }
        
        filterChain.doFilter(request, response);
    }
} 